import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { findUserById } from '../models/User';

// 扩展Request接口以包含用户信息
export interface AuthRequest extends Request {
  user?: {
    id: number;
    username: string;
    email: string;
    chips: number;
  };
}

// 验证JWT令牌的中间件
export const authenticateToken = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => {
  try {
    // 从请求头获取令牌
    const authHeader = req.headers.authorization;
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
    
    if (!token) {
      res.status(401).json({ success: false, message: '访问令牌缺失' });
      return;
    }
    
    // 验证令牌
    const jwtSecret = process.env.JWT_SECRET;
    if (!jwtSecret) {
      res.status(500).json({ success: false, message: '服务器配置错误' });
      return;
    }
    
    const decoded = jwt.verify(token, jwtSecret) as { id: number };
    
    // 获取用户信息
    const user = await findUserById(decoded.id);
    if (!user) {
      res.status(401).json({ success: false, message: '用户不存在' });
      return;
    }
    
    // 将用户信息添加到请求对象
    req.user = {
      id: user.id,
      username: user.username,
      email: user.email,
      chips: user.chips
    };
    
    next();
  } catch (error) {
    console.error('认证错误:', error);
    res.status(403).json({ success: false, message: '无效的访问令牌' });
  }
};